package com.xbn.xbnmall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author XBN
 * @date 2020/8/13 20:28
 * @email 78742541@qq.com
 */
@Controller
public class LoginController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@ResponseBody
        @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token)
        {
            //其它服务器拿着token在验证服务器这里获取用户信息
            String s=stringRedisTemplate.opsForValue().get(token);
            return s;
        }
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url")String redirectUrl,
                            @CookieValue(value = "sso_token",required = false) String sso_token,
                            Model model){
        //如果当前浏览器带着sso_token 就说明该用户之前在某个系统登陆过了，不需要再登陆了
        if(!StringUtils.isEmpty(sso_token))
        {
            return "redirect:"+redirectUrl+"?token="+sso_token;
        }

        //登陆成功要跳转到登陆之前的页面
        model.addAttribute("url",redirectUrl);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLoogin(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("url")  String url,
                           HttpServletResponse response){
            if(!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password))
            {
                //登陆成功
                String uuid= UUID.randomUUID().toString().replace("-","");
                stringRedisTemplate.opsForValue().set(uuid,username);
                //给用户的浏览器留一个cookie标识用户已经登陆过了。
                //这个cookie是针对于认证服务器的
                Cookie sso_token = new Cookie("sso_token", uuid);
                response.addCookie(sso_token);
                return "redirect:"+url+"?token="+uuid;
            }
            else {
                //登陆失败
                return "login";
            }

    }
}
